<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/10
 * Time: 下午5:56
 */
namespace App\Utility;

use MysqliDb;
use Swoole\Process\Pool;
use EasySwoole\Trigger\Trigger;
use EasySwoole\EasySwoole\Config;

/**
 * 连接MySql数据库进行操作
 * @author Administrator
 */
class MysqlNewPool extends Pool
{

    /**
     * 获取当前连接
     *
     * {@inheritdoc}
     * @return object MySQL连接对象
     */
    function getObj($timeOut = 0.1): ? MysqliDb
    {
        return parent::getObj($timeOut);
    }

    /**
     * 创建MySQL连接
     * {@inheritdoc}
     * @return object MySQL连接对象
     */
    protected function createObject() {
        $dbConf = [];
        try {
            $conf = Config::getInstance()->getConf('MYSQL');
            $dbHost = isset($conf['host']) ? $conf['host'] : 'localhost';
            $dbUser = isset($conf['user']) ? $conf['user'] : 'root';
            $dbPwd = isset($conf['password']) ? $conf['password'] : '';
            $dbName = isset($conf['database']) ? $conf['database']: 'null';
            $dbConf = array("host"=> $dbHost,"username"=>$dbUser,"password"=>$dbPwd,"db"=> $dbName);
            $db = new MysqliDb($dbHost,$dbUser,$dbPwd,$dbName);
            if (isset($conf['charset'])  && !empty($conf['charset'])) {  $db->rawQuery('SET NAMES ' . $conf['charset']); }   //设置编码
            BaseEnum::Logger('创建MySQL连接池:MysqlNewPool-(createObject)-创建成功;', 'user-login');
            return $db;
        } catch (\Throwable $throwable) {
            Trigger::throwable($throwable);
            BaseEnum::Logger('创建MySQL连接池异常：->'.$throwable->getCode()  ."==". json_encode($dbConf) . "MSG:" . $throwable->getMessage(), 'user-login');
            return null;
        }
    }
}
